<!--
 * @Author: LiZhiWei
 * @Date: 2025-07-22 14:50:58
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 11:15:04
 * @Description: 
-->
<template>
  <Content>
    <el-tabs :model-value="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane v-if="checkAction(actions.profile)" label="修改资料" name="profile" :lazy="true">
        <MeProfile :entity="entity" />
      </el-tab-pane>
      <el-tab-pane
        v-if="checkAction(actions.password)"
        label="修改密码"
        name="password"
        :lazy="true"
      >
        <MePassword :entity="entity" />
      </el-tab-pane>
      <el-tab-pane v-if="checkAction(actions.avatar)" label="修改头像" name="avatar" :lazy="true">
        <MeAvatar :entity="entity" />
      </el-tab-pane>
      <el-tab-pane v-if="checkAction(actions.logins)" label="登录管理" name="logins" :lazy="true">
        <MeLogins />
      </el-tab-pane>
      <el-tab-pane v-if="checkAction(actions.logins)" label="通知助手" name="robot" :lazy="true">
        <NotifyRobot />
      </el-tab-pane>
    </el-tabs>
  </Content>
</template>

<script setup lang="ts">
  import type { TabsPaneContext } from 'element-plus'

  import { watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import checkAction from '#/utils/check-action'
  import MeLogins from '#/views/me/components/me-logins.vue'
  import NotifyRobot from '#/views/me/components/notify-robot.vue'

  import MeAvatar from './components/me-avatar.vue'
  import MePassword from './components/me-password.vue'
  import MeProfile from './components/me-profile.vue'

  defineOptions({
    name: 'Me',
  })

  const entity = 'Me'

  const router = useRouter()
  const route = useRoute()
  const defaultTab = ref('profile')
  const activeName = ref('profile')
  const actions = ref({
    profile: 'system-admin-index',
    avatar: 'system-admin-avatar',
    password: 'system-admin-password',
    update: 'system-admin-update',
    notify: 'system-admin-notify',
    logins: 'system-admin-index',
    robot: 'system-admin-index',
  })

  // 监听路由变化，切换 tab
  watch(
    () => router.currentRoute.value.fullPath,
    (newPath) => {
      activeName.value = newPath.replace('/me/index?tab=', '')
    }
  )

  const handleClick = (tab: TabsPaneContext) => {
    const query = { ...route.query, tab: tab.paneName }
    router.replace({ path: route.path, query })
  }

  const checkActiveName = () => {
    const tab: PickKeysEnum<typeof actions.value> =
      (route.query.tab as PickKeysEnum<typeof actions.value>) ?? defaultTab.value

    if (checkAction(actions.value[tab]) && activeName.value !== tab) {
      activeName.value = tab
    }
  }

  onMounted(() => {
    checkActiveName()
  })
</script>
